package com.auxgroup.hr.front.service.process.impl;

import com.alibaba.fastjson.JSON;
import com.auxgroup.hr.front.commons.exception.ValidationException;
import com.auxgroup.hr.front.commons.utils.DateUtils;
import com.auxgroup.hr.front.commons.utils.ObjectFieldUtils;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dao.domain.*;
import com.auxgroup.hr.front.dao.repository.PsCWfEmpVwRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfGoutDtlRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfGoutHdrRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfWkotDtlRepository;
import com.auxgroup.hr.front.dozer.IObjectMapper;
import com.auxgroup.hr.front.hrverify.AuxCheckRequest;
import com.auxgroup.hr.front.hrverify.AuxCheckResponse;
import com.auxgroup.hr.front.service.comm.SysDictService;
import com.auxgroup.hr.front.service.process.WfFileService;
import com.auxgroup.hr.front.service.process.WfGoutHdrService;
import com.auxgroup.hr.front.service.process.WfGoutHdrService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 外出服务
 */
@Service("wfGoutHdrService")
public class WfGoutHdrServiceImpl implements WfGoutHdrService {
    private static final Logger logger = LoggerFactory.getLogger(WfGoutHdrServiceImpl.class);

    @Autowired
    private PsCWfGoutHdrRepository psCWfGoutHdrRepository;
    @Autowired
    private WfInitServiceImpl wfInitService;
    @Autowired
    protected SysDictService sysDictService;

    @Autowired
    private WfFileService wfFileService;

    @Resource(name = "dozerMapper")
    protected IObjectMapper objectMapper;

    @Autowired
    private PsCWfEmpVwRepository psCWfEmpVwRepository;
    @Autowired
    private PsCWfGoutDtlRepository psCWfGoutDtlRepository;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${auxgroup.hr.business.procUrl}")
    private String procUrl;

    @Override
    public List<PsCWfGoutDtl> queryByNbr(String cTransactionNbr) {
        return psCWfGoutDtlRepository.findByCTransactionNbr(cTransactionNbr);
    }

    @Override
    public PsCWfGoutHdr getWfInfo(String transNum) {
        return psCWfGoutHdrRepository.findOne(transNum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PsCWfGoutHdr saveWfInfo(PsCWfGoutHdr Gout, UserDTO user) {
        PsCWfGoutHdr goutHdr = psCWfGoutHdrRepository.findOne(Gout.getcTransactionNbr());
        if (goutHdr == null) {
            if (!valide(Gout, user)) {
                logger.info("HR 校验不通过", Gout);
                //throw new ValidationException("", "加班校验不通过");
            }
            //FIXME 当前只处理自己提交的加班
            JobCurrPrimary primary = new JobCurrPrimary();
            primary.setEmplid(user.getEmplId());
            primary.setEmplRcd(new BigDecimal(0));
            PsCWfEmpVw vw = psCWfEmpVwRepository.findOne(primary);
            goutHdr = objectMapper.map(vw, PsCWfGoutHdr.class);


            //FIXME 单个子表处理
            goutHdr = wfInitService.init(goutHdr, user, Gout.getcTransactionNbr());
            goutHdr.fillHdr4Self(vw);
            PsCWfGoutDtl dtl = new PsCWfGoutDtl();
            dtl.setEmplid(goutHdr.getEmplid());
            dtl.setcJobLevel(vw.getcJobLevel());
            dtl.setcTransactionNbr(goutHdr.getcTransactionNbr());
            dtl.setDeptid(vw.getDeptid());
            dtl.setName(vw.getNameDisplay());
            dtl.setRsFullName(vw.getRsFullName());
            psCWfGoutDtlRepository.save(dtl);

            //FIXME
//			goutHdr.setcOtherExplain(Gout.getcApplInfo());
            ObjectFieldUtils.handleNullValue(goutHdr);
        }

        goutHdr.baseInit(Gout);
        List<String> auxSystemInfoList = sysDictService.getAuxSystemInfo(user.getOprId());
        if (auxSystemInfoList != null && auxSystemInfoList.size() > 0) {
            goutHdr.setcIsAuxSystem("Y");
        } else {
            goutHdr.setcIsAuxSystem("N");
        }
        goutHdr.setcOaDbNm(" ");
        goutHdr.setUrl(" ");
        goutHdr.setLastupdoprid(user.getOprId()); // 更新者
        goutHdr.setLastupddttm(new Timestamp(System.currentTimeMillis())); // 更新时间
        return psCWfGoutHdrRepository.save(goutHdr);
    }


    @Override
    public void delWfInfo(String transNum) {
        wfFileService.delWfFiles(transNum, true);
        psCWfGoutHdrRepository.deleteByTransNum(transNum);
    }

    /**
     * @BillType varchar(100),   --=单据类型,对应考勤系统中的的单据类型名称
     * @IsAllDay varchar(1) = 'N',--外出类有效，表明是否直接是全天外出。注意一点是如果是全天假，那么跨天人员的最后一天，应该就是班次所在的日期。--
     * @IsResult varchar(1) = 'N',--是否直接写结果
     * @Reason varchar(500) = '',--原因
     * @AddDay datetime = getdate, --填单日
     * @MjArea varchar(8000) = '',--目的区域,建筑,可多选--格式:  '区域1-建筑1','区域2-建筑2'
     * @BillNo varchar(50)='' --单据号"
     */
    private boolean valide(PsCWfGoutHdr gout, UserDTO user) {
        AuxCheckRequest valReq = new AuxCheckRequest("udp_AuxTripCheck");
        valReq.add("EmpNo", user.getEmplId());

        valReq.add("BDateTime", DateUtils.format(gout.getDate1(), "yyyy-MM-dd") + gout.getcHour().replace('A', ' ') + ":" + gout.getcMinute())
                .add("EDateTime", DateUtils.format(gout.getDate2(), "yyyy-MM-dd") + gout.getcHour1().replace('A', ' ') + ":" + gout.getcMinute1())
                .add("BillType", "本地出差")
                .add("IsAllDay", "N")
                .add("IsResult", "Y")
                .add("Reason", gout.getcApplInfo())
                .add("AddDay", DateUtils.format(new Date(), "yyyy-MM-dd"))
                .add("MjArea", gout.getcArrival())
                .add("BillNo", "");//FIXME

        AuxCheckResponse resp = restTemplate.postForObject(procUrl, valReq, AuxCheckResponse.class);
        logger.info("HR 校验 {}", JSON.toJSONString(resp));
        if (!resp.isChecked("returnvalue", "Y")) {
            return false;
        }

        return true;
    }
}
 